<template>
  <div class="baseTable" ref="baseTableBox">
    <div class="edit-table-toolbar__title">
      {{ title }}
    </div>
    <el-table
      :data="tableConfig.data"
      border
      stripe
      :highlight-current-row="tableConfig.highlightRow"
      :header-cell-style="headerStyle"
      :height="tableConfig.autoHeight ? null : tableConfig.height || null"
      :max-height="tableConfig.maxHeight || null"
      :cell-style="tableConfig.cellStyle ? tableConfig.cellStyle : null"
      @row-click="tableConfig.rowClick($event) || clickChange"
      @selection-change="(val)=>{selectArr= val}"
      :span-method="tableConfig.spanMethod"
      ref="tableDataNode"
      @expand-change="expand"
      row-key="id"
      :row-class-name="rowStyle"
    >
      <el-table-column
        v-if="tableConfig.selectShow || false"
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="tableConfig.indexShow || false"
        label="序号"
        type="index"
        align="center"
        width="55"
      ></el-table-column>
      <template v-if="tableConfig.type == 'expand'">
        <el-table-column type="expand" align="left">
          <template slot-scope="scope">
            <div class="expandTable">
              <el-table
                :data="tableConfig.expandData"
                max-height="240"
                border
                stripe
                :header-cell-style="headerStyle"
                v-loading="loading"
                ref="expandTable"
                :key="scope.row"
                :cell-style="
                  tableConfig.expandCellStyle
                    ? tableConfig.expandCellStyle
                    : null
                "
              >
                <el-table-column
                  type="index"
                  width="55"
                  align="center"
                  label="序号"
                ></el-table-column>
                <template v-for="(item, index) in tableConfig.expandColumn">
                  <el-table-column
                    :label="item.label"
                    :align="item.textAlign ? item.textAlign : null"
                    :width="item.width"
                    :prop="item.prop"
                    v-if="!item.hide"
                    :key="'_' + index"
                  >
                    <template slot-scope="scope">
                      <template v-if="item.type == 'button'">
                        <template v-for="(btnItem, btnIndex) in item.buttonArr">
                          <el-button
                            :type="btnItem.type || 'text'"
                            size="small"
                            :key="btnIndex"
                            v-if="btnItem.isShow(scope.row)"
                            @click.stop="btnItem.methods(scope.row, scope.$index)"
                            :icon="btnItem.icon"
                            >{{ btnItem.text }}</el-button
                          >
                        </template>
                      </template>
                      <span
                        :style="item.textStyle(scope.row)"
                        v-else-if="item.textFormatter"
                        >{{ item.textFormatter(scope.row) }}</span
                      >
                      <span class="text-pre-wrap" v-else>{{
                        item.formatter
                          ? item.formatter(scope.row)
                          : formatterNull(scope.row[scope.column.property])
                      }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </template>
        </el-table-column>
      </template>

      <template v-for="(item, index) in tableConfig.column">
        <el-table-column
          :label="item.label"
          :align="item.textAlign ? item.textAlign : 'null'"
          :width="item.width"
          :prop="item.prop"
          :key="index"
          v-if="!item.hide"
          :fixed="item.fixed || null"
          :render-header="item.addRedStar"
        >
          <!-- 如果是合并单元的表头 -->
          <template v-if="item.subColumn">
            <template v-for="(subItem, subIndex) in item.subColumn">
              <el-table-column
                :label="subItem.label"
                :align="subItem.textAlign ? subItem.textAlign : null"
                :width="subItem.width"
                :prop="subItem.prop"
                :key="subIndex"
                v-if="!subItem.hide"
                :fixed="subItem.fixed || null"
              >
                <template slot-scope="scope">
                  <template v-if="subItem.type == 'button'">
                    <template v-for="(btnItem, btnIndex) in subItem.buttonArr">
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="btnItem.content"
                        :disabled="!btnItem.disabled"
                        :placement="btnItem.placement || 'top'"
                        :key="btnIndex"
                      >
                      <div style="display: inline-block; margin: 0 5px">
                        <el-button
                          :type="btnItem.type || 'text'"
                          size="small"
                          v-if="btnItem.isShow(scope.row)"
                          @click.stop="btnItem.methods(scope.row)"
                          :disabled="btnItem.disabled"
                          :icon="btnItem.icon"
                          >{{ btnItem.text }}</el-button
                        >
                      </div>
                      </el-tooltip>
                    </template>
                  </template>
                  <template v-else>
                    <span
                      :style="subItem.textStyle(scope.row)"
                      v-if="subItem.textFormatter"
                      >{{ subItem.textFormatter(scope.row) }}</span
                    >
                    <el-tooltip
                      effect="dark"
                      v-if="subItem.showTooltip"
                      placement="top"
                      :content="
                        subItem.formatter
                          ? subItem.formatter(scope.row)
                          : subItem.text
                          ? formatterNull(scope.row[subItem.text])
                          : formatterNull(scope.row[scope.column.property])
                      "
                    >
                      <span
                        class="table-cloumn__span--tooltip w100"
                        style="display: inline-block"
                        >{{
                          subItem.formatter
                            ? subItem.formatter(scope.row)
                            : subItem.text
                            ? formatterNull(scope.row[subItem.text])
                            : formatterNull(scope.row[scope.column.property])
                        }}</span
                      >
                    </el-tooltip>
                    <span
                      v-else-if="subItem.scopeType == 'formate'"
                      v-html="
                        subItem.method(scope.row)
                          ? subItem.method(scope.row)
                          : emptyStyle
                      "
                    ></span>
                    <span v-else class="text-pre-wrap">{{
                      subItem.formatter
                        ? subItem.formatter(scope.row)
                        : formatterNull(scope.row[scope.column.property])
                    }}</span>
                  </template>
                </template>
              </el-table-column>
            </template>
          </template>
          <template slot-scope="scope">
            <template v-if="item.type == 'button'">
              <template v-for="(btnItem, btnIndex) in item.buttonArr">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="btnItem.content"
                  :disabled="!btnItem.disabled"
                  :placement="btnItem.placement || 'top'"
                  :key="btnIndex"
                >
                <div style="display: inline-block; margin: 0 5px">
                  <el-button
                    :type="btnItem.type || 'text'"
                    size="small"
                    v-if="btnItem.isShow(scope.row)"
                    :disabled="btnItem.disabled"
                    @click.stop="btnItem.methods(scope.row, scope.$index)"
                    :icon="btnItem.icon"
                    >{{ btnItem.text }}</el-button
                  >
                </div>
                </el-tooltip>
              </template>
            </template>
            <template v-else-if="item.type == 'check'">
              <template>
                <el-checkbox
                  :true-label="1"
                  :false-label="0"
                  v-model="scope.row[scope.column.property]"
                  @change="changeCheck"
                ></el-checkbox>
              </template>
            </template>
            <template v-else-if="item.type == 'textButton'">
              <el-button
                type="text"
                size="small"
                @click.stop="
                  item.method ? item.method(scope.row, scope.$index) : null
                "
                >{{ scope.row[item.prop] }}</el-button
              >
            </template>
            <template v-else-if="item.type === 'textarea'">
              <el-input
                type="textarea"
                autosize
                :rows="1"
                @blur="inputBlur(scope.row)"
                v-model="scope.row[scope.column.property]"
                placeholder="请输入"
              ></el-input>
            </template>
            <template v-else-if="item.type === 'textareaBtn'">
              <div
                @click="
                  item.method ? item.method(scope.row, scope.$index) : null
                "
              >
                <span class="input-link">{{
                  item.formatter
                    ? item.formatter(scope.row)
                    : formatterNull(scope.row[scope.column.property])
                }}</span>
              </div>
            </template>
            <template v-else-if="item.type == 'switch'">
              <el-switch
                @change="inputBlur(scope.row)"
                class="switch"
                v-model="scope.row[scope.column.property]"
                :active-value="item.activeValue || 1"
                active-color="#1890ff"
                :active-text="item.activeText || '是'"
                :inactive-value="item.inactiveValue || 0"
                inactive-color="#ccc"
                :inactive-text="item.inactiveText || '否'"
                :disabled="item.disabled || false"
              >
              </el-switch>
            </template>
            <template v-else>
              <span
                :style="item.textStyle(scope.row)"
                v-if="item.textFormatter"
                >{{ item.textFormatter(scope.row) }}</span
              >
              <el-tooltip
                effect="dark"
                v-if="item.showTooltip"
                placement="top"
                :content="
                  item.formatter
                    ? item.formatter(scope.row)
                    : item.text
                    ? formatterNull(scope.row[item.text])
                    : formatterNull(scope.row[scope.column.property])
                "
              >
                <span
                  class="table-cloumn__span--tooltip w100"
                  style="display: inline-block"
                  >{{
                    item.formatter
                      ? item.formatter(scope.row)
                      : item.text
                      ? formatterNull(scope.row[item.text])
                      : formatterNull(scope.row[scope.column.property])
                  }}</span
                >
              </el-tooltip>
              <span
                v-else-if="item.scopeType == 'formate'"
                v-html="
                  item.method(scope.row) ? item.method(scope.row) : emptyStyle
                "
              ></span>
              <span v-else class="text-pre-wrap">{{
                item.formatter
                  ? item.formatter(scope.row)
                  : formatterNull(scope.row[scope.column.property])
              }}</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div class="kr-table-pagination">
      <el-pagination
        v-if="tableSetting.showPagination || false"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableSetting.searchForm.page"
        :page-sizes="paginationObj.pageSizes"
        :page-size="tableSetting.searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableSetting.totalNumber"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    tableSetting: {
      type: Object,
      default: () => {
        return {};
      },
      tableData: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    //分页对象
    paginationObj: {
      type: Object,
      default: () => {
        return { pageSizes: [15, 30, 50, 100] };
      },
    },
  },
  data() {
    return {
      tableConfig: {
        column: [],
        expandColumn: [],
        expandData: [],
        data: [],
        noBorderRight: true,
        autoHeight: false,
        highlightRow: true,
        spanMethod: () => {},
        rowClick: () => {},
      },
      loading: false,
      currentrow: {},
      selectArr: [],
      emptyStyle: `-`,
      title: "",
    };
  },
  created() {
    this.init();
  },
  computed: {
    headerStyle() {
      let style = {
        background: "#fafafa",
        color: "#333333",
        fontWeight: "bold",
        borderBottom: "1px solid #ebebeb",
        padding: 0,
      };
      if (this.noBorderRight) {
        style.borderRight = "none";
      }
      return style;
    },
  },
  watch: {
    tableSetting: {
      handler(val) {
        this.tableConfig = Object.assign({}, this.tableConfig, val);
      },
      deep: true,
    },
    tableData: {
      handler(val) {
        if (val.length > 0) {
          this.setTableData(val);
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.setTableHeight();
  },
  methods: {
    init() {
      this.tableConfig = Object.assign({}, this.tableConfig, this.tableSetting);
      let { title, data } = this.tableSetting;
      /* 优先tableData里面的值 */
      let len = this.tableData ? this.tableData.length : 0;
      if (len > 0) {
        this.tableConfig.data = this.tableData;
      }
      this.title = title || "";
    },
    // headerStyle() {
    //   return {
    //     borderRight: "none",
    //   };
    // },
    //表格页显示数量改变
    handleSizeChange(val) {
      this.tableSetting.searchForm.page = 1;
      this.tableSetting.searchForm.pageSize = val;
      this.tableSetting.searchObj.searchMethod(this.tableSetting.searchForm);
    },
    //表格页码改变
    handleCurrentChange(val) {
      this.tableSetting.searchForm.page = val;
      this.tableSetting.searchObj.searchMethod(this.tableSetting.searchForm);
    },
    //行样式
    rowStyle({ row }) {
      if (this.tableConfig.rowClick.toString().includes("{}")) {
        return `noClickedRowHover`;
      } else {
        return `clickedRowHover`;
      }
    },
    setTableData(data) {
      this.tableConfig.data = JSON.parse(JSON.stringify(data));
    },
    //清除多选
    clearSelection() {
      this.$refs.tableDataNode.clearSelection();
    },
    // 输入框失去焦点
    inputBlur(row) {
      this.$emit("saveData", row);
    },
    //追加data
    pushData(data) {
      let arr = [...data];
      arr.map((i) => {
        this.tableConfig.data.push(i);
      });
    },
    setExpandTableData(data) {
      this.$set(this, "loading", false);

      this.$set(
        this.tableConfig,
        "expandData",
        JSON.parse(JSON.stringify(data))
      );
    },
    changeCheck(val) {},
    clickChange(row) {
      if (this.currentrow) {
        if (this.currentrow.id != row.id) {
          this.$refs["tableDataNode"].toggleRowExpansion(
            this.currentrow,
            false
          );
        } else {
          this.$refs["tableDataNode"].toggleRowExpansion(row, false);
          this.currentrow = null;
          return;
        }
      }
      this.$refs["tableDataNode"].toggleRowExpansion(row, true);
    },
    setCurrentRow(node) {
      this.$refs["tableDataNode"].setCurrentRow(node);
    },
    //展开事件
    expand(row, expandrow) {
      if (this.currentrow) {
        if (this.currentrow.id != row.id) {
          this.$refs["tableDataNode"].toggleRowExpansion(
            this.currentrow,
            false
          );
          this.$set(this, "currentrow", row);
        } else {
          this.$set(this, "currentrow", null);
          return;
        }
      }
      this.$set(this, "currentrow", row);
      this.loading = true;
      this.$emit("expandRow", row);
    },
    //获取table数据
    getTableData() {
      let arr = JSON.parse(JSON.stringify(this.tableConfig.data));
      return arr;
    },
    /**判断空值默认- */
    formatterNull(text) {
      if (text === null || text === undefined || text === "") {
        return "-";
      } else {
        return text;
      }
    },
    /**设置最大高度 */
    setTableHeight() {
      let { height, maxHeight, autoHeight } = this.tableSetting;
      if (!height && !maxHeight && !autoHeight) {
        let parentH = this.$refs.baseTableBox.parentElement.clientHeight;
        parentH = parentH - 36;
        this.tableConfig.height = parentH < 200 ? 200 : parentH;
      }
    },
    //获取选中的行
    getCheckedRow(){
      return this.selectArr
    }
  },
};
</script>
<style lang="less" scoped>
/deep/ .el-table tr {
  height: 40px;
}
/deep/ .el-table td {
  border-bottom: 1px solid #ebeef5;
}
.edit-table-toolbar__title {
  font-weight: bold;
  margin-left: 10px;
  text-align: left;
  margin-bottom: 10px;
}
.baseTable {
  height: 100%;
}
.expandTable {
  padding: 10px 40px;
}
.table-cloumn__span--tooltip {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
/deep/ .el-input__inner {
  height: 30px;
  line-height: 30px;
  border-radius: 2px;
}
/deep/ .switch .el-switch__label {
  position: absolute;
  display: none;
  color: #fff !important;
}
/deep/ .switch .el-switch__label--right {
  z-index: 1;
}
/deep/ .switch .el-switch__label--right span {
  margin-left: -5px;
}
/deep/ .switch .el-switch__label--left {
  z-index: 1;
}
/deep/ .switch .el-switch__label--left span {
  margin-left: 21px;
}
/deep/ .switch .el-switch__label.is-active {
  display: block;
}
.input-link {
  cursor: pointer;
  color: royalblue;
  white-space: pre-line;
}
.text-pre-wrap {
  white-space: pre-line;
}
.kr-table-pagination {
  margin-top: 5px;
  text-align: right;
}
</style>


